String.prototype.format = function() {
    var s = this,
        i = arguments.length;
    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

/* util.js */
function push_to_google(data) {
    if(window.is_debug) {
        console.log(data);
    }
    _gaq.push(data);
}

function push_contact_view(company_yandex_tracker, company_site_yandex_tracker) {
    // Inform Google and Yandex that company's contacts is viewed
    if(!document.contact_view_executed) {
        var yaCounter;
        push_to_google(['_trackEvent', 'buyer_conversion_tracking', 'company_contacts_viewed']);
        push_to_google(['_trackEvent', 'Contact view', 'contact_block_mouse_over', window.page_type || 'undefined']);
        if(window.yandex_metrics_code) {
            yaCounter = window['yaCounter' + window.yandex_metrics_code];
            if(yaCounter) {
                yaCounter.reachGoal('company_contacts_viewed');
            }
        }
        if(company_yandex_tracker && window.show_stats) {
            yaCounter = window['yaCounter' + company_site_yandex_tracker || company_yandex_tracker];
            if(yaCounter) {
                yaCounter.reachGoal('company_contacts_viewed');
            }
        }
        document.contact_view_executed = true;
    }
}

function hasAttribute(element, attribute_name) {
    try {
        str = "element." + attribute_name;
        if (eval(str) != undefined)
            return true;
    } catch (e) { }

    return false;
}

function show_element(element, display_method) {
    if (!display_method) {
        display_method = 'block';
    }
    element = $(element);
    element.style.display = display_method;
}

function hide_element(element) {
    element = $(element);
    element.style.display = 'none';
}

function $(element) {
    if (!hasAttribute(element, "id")) {
        try {
            element = document.getElementById(element);
        } catch (e) {
        }
    }
    return element;
}

function is_visible(element) {
    element = $(element);
    return element.style.display != 'none';
}

function two_digits(param) {
    param = "" + param;
    while (param.length < 2) {
        param = "0" + param;
    }
    return param;
}

function is_type_text(element) {
    return element.type == "text";
}
function is_type_checkbox(element) {
    return element.type == "checkbox";
}
function is_type_select_one(element) {
    return element.type == "select-one";
}
function is_type_radio(element) {
    return element.type == "radio";
}
function is_type_radio_group(element) {
    return element.length && is_type_radio(element[0]);
}
function is_type_label(element) {
    return element.tagName.toLowerCase() == "label";
}

function asbool(value) {
    value = trim(String(value).toLowerCase());
    switch (value) {
    case "true":
    case "1":
    case "yes":
    case "on":
        return true;
    case "false":
    case "0":
    case "no":
    case "off":
        return false;
    }
    throw "Not a boolean value - " + value;
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}
var strip = trim;

function group_set_property(elements_ids, property, value) {
    for (i in elements_ids) {
        eval("document.getElementById('" + elements_ids[i] + "')." + property + " = " + value);
    }
}
function group_set_checked(elements_ids, checked) {
    group_set_property(elements_ids, "checked", checked);
}
function group_conjunct_property(elements_ids, property) {
    result = true;
    for (i in elements_ids) {
        eval("result = result && document.getElementById('" + elements_ids[i] + "')." + property);
        if (!result) {
            break;
        }
    }
    return result;
}

function get_radio_value(radio_element) {
    for (var i = 0; i < radio_element.length; i++) {
	if (radio_element[i].checked) {
	    return radio_element[i].value
	}
    }
    return null;
}
/* end util.js */

/* promua.js */
function collapse_change_state(collapsed_id) {
	$$('#'+collapsed_id).toggle();
	$$('#'+collapsed_id+'_img').toggleClass('open');
}
function collapse_change_state_horisontal(collapsed_id, link, expand_text, collapse_text) {
    var $a = $$(link);
    var $collapsed_block = $$("#"+collapsed_id);
    var closed = $a.find(".closed");
    var opened = $a.find(".opened");
    $collapsed_block.toggle();

    if ($collapsed_block.is(":visible")) {
        $a.find(".collapse-text").text(collapse_text);
        $a.find("#collapse_img").removeClass("collapsed");
        opened.show(); closed.hide();
    }
    else {
        $a.find(".collapse-text").text(expand_text);
        $a.find("#collapse_img").addClass("collapsed");
        closed.show(); opened.hide();
    }
}
/* end promua.js */

//var YA = YAHOO.util.Anim;
function $(id) {
    return document.getElementById(id);
}
/**namespace for page globals**/
var Page = {}
Page.richEditors = {}

Page.popups = {
    pro_popup_header: "",
    pro_popup_is_cabinet: 0,
    pro_popup_packages: {},

    bind_delivery_popup: function(selector, ajax_url) {

        $$(selector).click(function(e){
            var id = $$(e.target).data("id");
            var $popup = $$(
                    "<div></div>",
                    {"id": "delivery_info_popup",
                     "class": "b-overlay b-overlay_type_dialog b-overlay_view_delivery-info"}
                ).appendTo("body");
            var overlay_params = {
                top: "20%",
                fixed: false,
                oneInstance: false,
                closeOnClick: true,
                onClose: function(e) {e.target.close(); $popup.remove()},
                mask: "#ccc"
            };
            $$.ajax({
                url: ajax_url,
                type: "GET",
                dataType: "html",
                data: {company_id: id},
                success: function(data) {
                    $popup.html(data);
                    $popup.overlay(overlay_params).overlay().load();;
                }
            });
        });
    },
    bind_pro_popup: function (header, is_cabinet) {
        $$('.pro-stars').hover(function(){
            $$(this).css('cursor', 'help');
        });
        this.pro_popup_header = header;
        if (is_cabinet) {
            this.pro_popup_is_cabinet = is_cabinet;
        }
        var header = header;
        var self = this;
        $$('.pro-stars').bind("click", load_popup);

        function load_popup(e) {
            var elem = $$(e.currentTarget);
            var pkg = $$(this).data("package");
            var pkg_name = $$(this).data("package_name");

            var selector = '.pro-stars'
            if (self.pro_popup_is_cabinet) {
                var selector = '.pro-stars[data-package='+pkg+']'
            }

            if (!self.pro_popup_packages[pkg]) {
                if (self.pro_popup_is_cabinet ) {
                    header = "";
                    header = self.pro_popup_header+' '+pkg_name;
                }
                self.pro_popup_packages[pkg] = true;
                $$.getJSON('/util/ajax_get_pro_popup_new/', {"pkg": pkg, "is_cabinet": self.pro_popup_is_cabinet}, function (data) {
                    $$(selector).unbind('click');
                    SW.helpPanel("pro_stars",
                        header,
                        data.html,
                        undefined,
                        $$(selector)
                    );
                    elem.click();
                });
            }
        }
    }
};

Page.popup_help = {
    popup_popuper: "",
    popup_header: "",
    popup_body: "",
    popup_params: {},
    popup_is_bound: false,
    format_data: {},
    bind_popup: function(popuper, header, body_text, params) {
        if (this.popup_is_bound) { return;}
        this.popup_is_bound = true;
        this.popup_header = header;
        this.popup_body = body_text;
        this.popup_popuper = popuper;
        if (params) {
            this.popup_params = params;
        }
        var self = this;
        $$(this.popup_popuper).hover(load_popup_help);
        $$(this.popup_popuper).mouseout(function (e) {
            $$(popuper+'-comics').parent().hide();
        });

        function load_popup_help(e) {
            var elem = $$(e.currentTarget);
            popup_help(
                this,
                self.popup_header,
                self.popup_body,
                self.popup_params,
                self.format_data
            );
        }
    }
};

Page.popup_help_on_click = {
    popup_popuper: "",
    popup_header: "",
    popup_body: "",
    popup_params: {},
    popup_is_bound: false,

    bind_popup_on_click: function(popuper, header, body_text, params) {
        if (this.popup_is_bound) { return;}
        this.popup_is_bound = true;
        this.popup_header = header;
        this.popup_body = body_text;
        this.popup_popuper = popuper;
        if (params) {
            this.popup_params = params;
        }
        var self = this;
        $$(this.popup_popuper).click(load_popup_help);

        function load_popup_help(e) {
            var elem = $$(e.currentTarget);
            popup_help(
                this,
                self.popup_header,
                self.popup_body,
                self.popup_params
            );
        }
    }
};

/**
   SW is a holder for SmartWeb developed custom scripts
**/

var SW = {
	bind: function(func, obj) {
	     var slice = Array.prototype.slice;
	     var args = slice.call(arguments, 2);
	     return function() {
	       return func.apply(obj || {}, args.concat(slice.call(arguments)));
	     };
	},

    clearErrors: function(form_elem) {
        if (form_elem === undefined)
            $$("span.error, span.error-icon").addClass("hidden");
        else
            $$(form_elem).find("span.error, span.error-icon").addClass("hidden");;
    },
    flatErrors: function (errors, prefix) {
        var flat_errors = {};

        if (prefix === undefined)
            prefix = "";

        for (var key in errors) {
            var val = errors[key];
            var sep = ".";

            if (parseInt(key).toString() == key)
                sep = "-";

            var name = key;
            if (prefix)
                name = prefix + sep + key;

            if (jQuery.isArray(val)) {
                var all_strings = true;
                for (var i = 0; i < val.length; i++) {
                    if (typeof val[i] !== "string") {
                        all_strings = false;
                        break;
                    }
                }
                if (all_strings)
                    flat_errors[name] = val.join("<br />");
                else
                    jQuery.extend(flat_errors, SW.flatErrors(val, name));
            }
            else if (typeof val == "string") {
                flat_errors[name] = val;
            }
            else {
                jQuery.extend(flat_errors, SW.flatErrors(val, name));
            }
        }

        return flat_errors;
    },
    renderErrors: function (json_data, form_elem) {
        var result = {};
        if (typeof(json_data) == 'string') {
            eval('result = ' + json_data);
        } else {
            result = json_data;
            if (result.errors) {
                result = result.errors;
            }
        }

        result = SW.flatErrors(result);

        var BIG = 100000;
        var minTop = BIG;
        var wTop = $$(window).scrollTop();
        var wHeight = $$(window).height();
        var wBottom = wTop + wHeight;

        for (var key in result) {
            var id = key.replace(/\./g, "\\.");
            var $error_div = $$('#' + id + '_error');
            if ($error_div.length == 0) {
                alert('No error container defined for: ' + key);
                continue;
            }
            var errors = result[key];
            if (errors instanceof Array)
                errors = errors.join("<br />");
            $error_div.html(errors).removeClass("hidden");
            var $error_icon_div = $$('#' + id + '_error_icon');
            $error_icon_div.removeClass("hidden");
            var top = $error_div.offset().top;
            if ((top < wTop || top > wBottom) && minTop > top) {
                minTop = top;
            }
        }
        if (minTop != BIG)
            return minTop;
        return null;
    },
    asyncFormSubmit: function(form, button, config) {
        button.set('disabled', true);
        window.setTimeout(function(){
            button.set('disabled', false);
        }, 20 * 1000);

        var config = YL.merge({
            validationSuccess: null,
            validationError: function(o) {
		        var minTop = SW.renderErrors(o.responseText, form);
                if (minTop)
                    window.scrollTo(0, minTop - 100);
            },
            validationFailure: function(o) {
                button.set('disabled', false);
                //alert('Error during validation')
                //DO NOTHIND, TODO log somehting in debug
            },
            handler: {
                success: function(o) {
                    SW.clearErrors();
		    button.set('disabled', false);
                    if (o.responseText == "OK") {
                        config.validationSuccess(o);
                    } else {
                        config.validationError(o);
                    }
                },
                failure: config.validationFailure
            },
            method: 'POST',
            url: form.action
        }, config == null ? {} : config);
        SW.refreshRichTexts();
        YC.setForm(form);
        YC.initHeader("X-CSRFToken", jQuery.cookie('csrf_token'));
        if (window.PromUserID) {
            YC.initHeader("X-PromUserID", window.PromUserID);
        }
        YC.asyncRequest(config.method, config.url, config.handler);
        return false;
    },
    validateSubmit: function(button, formSchema, protocol) {
        var htmlButton = button.getForm ? button._button : button;
        var form = htmlButton.form;
        if (!protocol) {
            protocol = document.location.protocol;
        }
        if (!protocol.match(/:$/)) {
            protocol += ':';
        }
        host = document.location.host;
        if (!host.match(/.*:\d+/)) {
            host += ':' + document.location.port ? document.location.port : '';
        }
        var url = protocol + '//' + host + '/validation/index/' + formSchema;
        if (form.validated) {
            return true;
        }
        this.asyncFormSubmit(form, button, {
            url: url,
            validationSuccess: function(o) {
                form.validated = true;
                button.set('disabled', false);
                htmlButton.click()
                button.set('disabled', true);
            }
        });
        return false;
    },
    submitInline: function(button, validationSuccess) {
        this.asyncFormSubmit(button.getForm(), button, {
            validationSuccess: validationSuccess
        });
        return false;
    },
    disableButtons: function($form) {
        $form = $$($form);
        $$.each($form.find(":submit"), function(index, elem) {
            var $elem = $$(elem);
            $elem.data("was_disabled", $elem.prop('disabled'));

            if ($elem.hasClass('ui-button')) {
                $elem.button('disable');
            }
            else {
                $elem.prop('disabled', true);
            }
        });

    },
    restoreButtons: function($form) {
        $form = $$($form);
        $$.each($form.find(":submit"), function(index, elem) {
            var $elem = $$(elem);
            if(!$elem.data("was_disabled")) {
                if($elem.hasClass('ui-button')) {
                    $elem.button('enable');
                }
                else {
                    $elem.removeAttr('disabled');
                }
            }
        });
    },
    validateSubmitForm: function(o) {
        var $form, $button;
        if (o.button) {
            $button = $$(o.button);
            $form = $$(o.button.form);
        }
        else if (o.form) {
            $form = $$(o.form);
            $button = $form.find(":submit").first();
        }
        else {
            alert("You must specify button or form option.");
        }

        if($form.data('validated'))
            return true;

        SW.disableButtons($form);
        var config = $$.extend({
            button: null,
            saveOnValidation: false,
            url: $form.attr('action') || document.location.href,
            method: 'POST',
            validationSuccess: function (json, textStatus, xhr) {
                if ($form.data('callback')) {
                    $form.data('callback')(json);
                }
                else if (json.save_) {
                    if (json.next) {
                        document.location = json.next;
                    }
                    else if (json.messages) {
                        $$(document).scrollTop(0);
                        SW.clearErrors($form);
                        $$("#messages").empty();
                        for (key in json.messages) {
                            $$.tmpl('<li class="${type}">{{html message}}</li>', {"type": key, "message": json.messages[key]}).hide().appendTo("#messages").fadeIn();
                        }
                        SW.restoreButtons($form);
                        $$(document).trigger("uaprom.objectSaved", [json]);
                    }
                }
                else {
                    $form.data('validated', true);
                    SW.restoreButtons($form);
                    //$button.click(); // does'n work in firefox, i don't know why???
                    setTimeout(function () { $button.click(); }, 100);
                }
            },
            validationError: function (json, textStatus, xhr) {
                if ($form.data('callback_error')) {
                    $form.data('callback_error')(json);
                }
                SW.clearErrors($form);
                var minTop = SW.renderErrors(json, $form);
                if (minTop) {
                    window.scrollTo(0, minTop - 100);
                }
                SW.restoreButtons($form);
            }
        }, o || {});

        var form_data = $form.serializeArray();
        if (config.saveOnValidation) {
            form_data.push({"name": "save_", "value": "1"})
        }

        $$.ajax({
            type: config.method,
            url: config.url,
            data: $$.param(form_data),
            dataType: 'text',
            success: function (data, textStatus, xhr) {
                try {
                    // suggest response is json
                    var json = $$.parseJSON(data);
                    if (json.status && json.status.toLowerCase() == "ok")
                        config.validationSuccess(json, textStatus, xhr);
                    else
                        config.validationError(json, textStatus, xhr);
                }
                catch (e) {
                    // response is html
                    if(data.toLowerCase() == "ok") {
                        config.validationSuccess(data, textStatus, xhr);
                    }
                    //else {
                    //    config.validationError({}, textStatus, xhr);
                    // }
                }
            },
            error: function (xhr, status, e) {
                if(config.error) {
                    config.error(xhr, status, e);
                }
                SW.restoreButtons($form);
            },
            complete: function (xhr, status) {
                if(config.complete) {
                    config.complete(xhr, status);
               }
            }
        });

        return false;
    },
    /** Common overlay manager used to show only one help menu
        on the page initialize lazily**/
    overlayManager: null,

    registerHelpHint: function(el, hint) {
        var elem = $$('#'+el);

        elem.attr('alt', hint);

        function showHint() {
            var elem = $$(this);
            if (!elem.val()) {
                elem.addClass('inline-hint');
                elem.val(elem.attr('alt'));
            }
        }

        function hideHint() {
            var elem = $$(this);
            if (elem.val() == elem.attr('alt')) {
                elem.removeClass('inline-hint');
                elem.val('');
            }
        }

        elem.live('focusin', hideHint);
        elem.live('focusout', showHint);
        elem.live('mouseover', hideHint);
        elem.live('mouseout', showHint);
        elem.trigger('mouseout');
    },

    helpPanel: function (element_id, header, body, overlay_params, element) {
        var el = (element != undefined ? element : $$('#' + element_id));
        var $dialog = this.createOverlay(element_id, header, body, overlay_params);
        el.click(function() {
            $dialog.load();
            return false;
        });
        $$(document).click(function(e){
            $dialog.close();
        });
        element = el = body = header = overlay_params = null;
    },

    createOverlay: function (element_id, header, body, overlay_params) {
        overlay_params = $$.extend({closeOnClick: true, top: "25%", fixed: false, closeOnEsc: true}, overlay_params);
        var $dialog = $$("<div></div>", {'id': "popup_container_" + element_id.replace(/\\./g, '\.'), 'class': "modal info-popup"});
        $dialog = $dialog.html(($$('<h2></h2>').html(header)));
        ($$('<div></div>').html(body)).appendTo($dialog);
        $dialog.appendTo('body');
        return $dialog.overlay(overlay_params).overlay();
    },

    closeOverlayOnClick: function (dialog_id, overlay_params, additional_verify) {
        overlay_params = $$.extend({closeOnClick: true, top: "25%", fixed: false, closeOnEsc: true}, overlay_params);

        $$(document.body).click(function(event){
            $target = $$(event.target);
            if ($target.attr('class') != 'pro-stars' &&
                $target.parent().attr('class') != 'icon-help' &&
                !$target.closest('.modal, .oh-button').length
            ) {
                if (additional_verify){
                    if (!additional_verify()){
                        return;
                    }
                }
                var $dialog = $$('#' + dialog_id).overlay(overlay_params);
                if ($dialog.length != 0) {
                    $dialog.close();
                }
            }
        });
    },

    registerHelpPanel: function (el, header, body) {
	    $$('#'+el).click(function() {
		    var position =  $$(this).offset();
		    var height = $$(this).height();
            var shadowWidth = 10;
            var left = position.left - $$(document).scrollLeft() - shadowWidth;
            var top = position.top - $$(document).scrollTop() + height;
	        var dlg_id = el + "_dialog", $dlg;

	        if(!$$("#" + dlg_id).length){
		        var dialog = $$("<div></div>", {id: el + "_dialog"}).append($$("<p></p>").html(body));
		        $dlg = $$(dialog).dialog({
                    autoOpen: false,
		            draggable: false,
		            resizable: false,
                    minHeight: 0,
                    title: header,
					dialogClass: "preview_panel",
		            position: [left, top]
		        }).css({"background-color": "#F2F2F2"});
            }
            else
                $dlg = $$("#" + dlg_id);

            if(left + $dlg.dialog("option", "width") > $$(document).width())
                left = $$(document).width() - $dlg.dialog("option", "width") - shadowWidth;
		    $dlg.dialog("option", "position", [left, top]).dialog("open");
        });
    },

    nicEditorButtons: ['fontFormat','bold','italic','underline','strikeThrough','undo', 'redo', 'left','center','right','ol','ul','indent','unindent','hr','link'],

    maxLength: function(objId, maxLength, monitorId, drop_value, set_zero) {
        drop_value = typeof(drop_value) != 'undefined' ? drop_value : true;
        set_zero = typeof(set_zero) != 'undefined' ? set_zero : false;
        var $this = $$("#" + objId);
        var $monitor = $$("#" + monitorId)
        // if tag is textarea and textarea has attribute maxLength, then lets use it
        if (0 !== $this.attr('maxlength') && -1 !== $this.attr('maxlength') && undefined !== $this.attr('maxlength')) {
            maxLength = $this.attr('maxlength');
        }
        $this.bind("change keyup", function (e) {
            var $this = $$(this);
            var len = $this.val().length;

            if (drop_value && len > maxLength) {
                $this.val($this.val().substring(0, maxLength));
            }

            // set initial value to counter
            if (monitorId) {
                if (set_zero && len > maxLength) {
                    $monitor.html("0");
                } else {
                    $monitor.html(maxLength - $this.val().length);
                }
            }
        }).change();
    },

    limitExecByInterval: function(fn, time) {
    	var lock, execOnUnlock, args;
    	return function() {
    	    args = arguments;
    	    if (!lock) {
    		lock = true;
    		var scope = this;
    		setTimeout(function(){
    		    lock = false;
    		    if (execOnUnlock) {
    			args.callee.apply(scope, args);
    			execOnUnlock = false;
    		    }
    		}, time);
    		return fn.apply(this, args);
    	    } else execOnUnlock = true;
    	}
    },
    loadScript: function(url, elementId) {
    	var oScript = document.createElement("script");
    	oScript.type = "text/javascript"
    	oScript.src = url;
    	if (elementId != null) {
    	    oScript.id = elementId;
    	}
    	document.body.appendChild(oScript);
    },
    richEditorForTextarea: function(nodeId) {
        Page.richEditors[nodeId] = new nicEditor({buttonList : SW.nicEditorButtons}).panelInstance(nodeId);
    },
    refreshRichTexts: function() {
        for (key in Page.richEditors) {
            // alert(Page.richEditors)
            // alert(Page.richEditors[key].nicInstances[0].getContent())
            YD.get(key).value = Page.richEditors[key].nicInstances[0].getContent()
        }
    },
    ButtonCodeViewer: function(codeAreaId){
   	var codeAreaObj = document.getElementById(codeAreaId);
   	var buttonsRegister = new Array();
	this.isRegisteredButton = function(buttonObj){
	    for (var i = 0; i < buttonsRegister.length; i ++) {
		if (buttonsRegister[i] == buttonObj) {
		    return true;
		}
	    }
	    return false;
	}
	this.click = function(buttonObj){
	    for (var i = 0; i < buttonsRegister.length; i ++) {
		buttonsRegister[i].className = buttonObj.defaultClass;
		buttonsRegister[i].selected = false;
	    }
	    if (!this.isRegisteredButton(buttonObj)) {
		buttonsRegister[buttonsRegister.length] = buttonObj;
	    }
	    buttonObj.className = 'promo-button-wrapper-selected';
	    buttonObj.selected = true;
	    codeAreaObj.value = buttonObj.innerHTML;
	    return false;
	}
	this.over = function(buttonObj){
	    if (buttonObj.defaultClass == null) {
		buttonObj.defaultClass = buttonObj.className;
	    }
	    buttonObj.className = 'promo-button-wrapper-selected';
	}
	this.out = function(buttonObj){
	    if (!buttonObj.selected) {
		buttonObj.className = buttonObj.defaultClass;
	    }
	}
    },
    expandCategoryList: function (listContainerId, expandButtonObj, removing_class){
	expandButtonObj.style.display = 'none';
    	var catagoryContainer = document.getElementById(listContainerId);
    	var categoryItems = catagoryContainer.getElementsByTagName("span");
    	for (var i = 0; i < categoryItems.length; i++){
    	    categoryItems[i].className = categoryItems[i].className.replace(removing_class?removing_class:"category-collapsed", "");
    	}
    	return false;
    },
    ColorSchemaToggle: function (){
    	var containerRegister = new Array();
    	this.isRegisteredContainer = function(containerObj){
    	    for (var i = 0; i < containerRegister.length; i ++) {
        		if (containerRegister[i] == containerObj) {
        		    return true;
        		}
	        }
	        return false;
	    }
    	this.click = function(containerNodeId){
    	    var containerNode = document.getElementById(containerNodeId);
    	    for (var i = 0; i < containerRegister.length; i ++) {
    		    containerRegister[i].className = "color-schema-wrapper";
    	    }
    	    containerNode.className = containerNode.className + " color-schema-wrapper-active";
    	    if (!this.isRegisteredContainer(containerNode)){
    	    	containerRegister[containerRegister.length] = containerNode;
    	    }
    	}
    },

    throttle: function(fn, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    }

    // toglePromoBlock: function(domainName) {
    //     function setCookie(value, domainName) {
    // 	    $$.cookie("show_promo_block", value, {
    //             path: "/",
    //             domain: domainName,
    //             expires: new Date(new Date().getTime() + 1000 * 3600 * 24 * 356 * 10)
    //         });
    //     }
    //     var promoContainer = $$('#promo-header-container');
    //     var collapsedRegisterBlockContainer = $$('#collapsed-promo-block-register-container');
    //     if ($$.cookie("show_promo_block") == "False") {
    //         promoContainer.attr('class', 'promo-header-expanded-wrapper');
    //         if (collapsedRegisterBlockContainer){
    //             collapsedRegisterBlockContainer.html('');
    //         }
    //         $$('#close_label_div').onmouseover = function() {  };
    //         $$('#close_label_div').onmouseout = function() {  };
    //         $$('#close_label_div').attr('style', 'backgroundColor: transparent;');
    //         setCookie("True", domainName);
    //     } else {
    // 	    promoContainer.attr('class', 'promo-header-collapsed-wrapper')
    //         if (collapsedRegisterBlockContainer){
    //             collapsedRegisterBlockContainer.html($$('#register-button-container').html());
    //         }
    //         $$('#close_label_div').onmouseover = function() { SW.anim.animate(); };
    //         $$('#close_label_div').onmouseout = function() { SW.anim_out.animate(); };
    //         setCookie("False", domainName);
    //     }
    // }
}

SW.c = new Object();

WTF = {
    TextField: {
        Clear: function(container_selector, name) {
            $$(container_selector+" input[name="+name+"]").val("");
        },
        Populate: function(container_selector, name, val) {
            $$(container_selector+" input[name="+name+"]").val(val);
        }
    },

    TextAreaField: {
        Clear: function(container_selector, name) {
            $$(container_selector+" textarea[name="+name+"]").val("");
        },
        Populate: function(container_selector, name, val) {
            $$(container_selector+" textarea[name="+name+"]").val(val);
        }
    },

    PriceField: {
        Clear: function(container_selector, name) {
            $$(container_selector+" input[name="+name+"]").val("");
        },
        Populate: function(container_selector, name, val) {
            $$(container_selector+" input[name="+name+"]").val(val);
        }
    },

    HiddenField: {
        Clear: function(container_selector, name) {
            $$(container_selector+" input[name="+name+"]").val("");
        },
        Populate: function(container_selector, name, val) {
            $$(container_selector+" input[name="+name+"]").val(val);
        }
    },

    BooleanField: {
        Clear: function(container_selector, name) {
            $$(container_selector+" input[name="+name+"]").removeAttr("checked");
        },
        Populate: function(container_selector, name, val) {
            if (asbool(val)) {
                $$(container_selector+" input[name="+name+"]").attr("checked", "checked");
            } else {
                $$(container_selector+" input[name="+name+"]").removeAttr("checked");
            }
        }
    }

}

function incr_element_value(element, value) {
    element = document.getElementById(element);
    element.innerHTML = Number(element.innerHTML) + value;
}

function update_functionality_price(check_box_element, price_show_element, comulative_price_element, price) {
    YAHOO.util.Event.on(check_box_element, "change", function(e) {
        if (e.target.checked) {
            YAHOO.util.Dom.get(price_show_element).innerHTML = price;
            incr_element_value(comulative_price_element, price);
        } else {
            YAHOO.util.Dom.get(price_show_element).innerHTML = 0;
            incr_element_value(comulative_price_element, -1*price);
        }
    });
}

collapse_table_rows = function(selector) {
    var $elem = $$(selector);
    if ($elem.hasClass("collapsed-rows")) {
        $elem.removeClass("collapsed-rows");
    } else {
        $elem.addClass("collapsed-rows");
    }
};

jQuery.fn.incrise_image = function(options) {
	var settings = {
      'dimension': 200,
      'speed': 300,
      'delay': 1000,
      'img_margin': 5,
      'box_min_dimension': 100
    };
    if(options) {
        jQuery.extend( settings, options );
    }
	var timeout;
	var border_space = settings.img_margin;

	function get_anim_model(incrise, parent){
		var model = this.anim_model;
		if (this.old_width >= this.old_height)
			return  parent ? (incrise ? model.incr_par_wide : model.decrise_all) : (incrise ? model.incr_img_wide : model.decrise_img_wide);
		else
			return parent ? (incrise ? model.incr_par_high : model.decrise_all) : (incrise ? model.incr_img_high : model.decrise_img_high);
	}

	function change_class(classes){
		jQuery(this).toggleClass(classes);
	}

	function cleartime(){
		clearTimeout(timeout);
	}

	return this.each( function() {
		var $this = jQuery(this);
		var self = this;
		var $img;

		function init_show(){
            if(options.is_bem){
                $this.css({
                    float: 'none',
                    position: 'absolute',
                    marginLeft: 0,
                    left: 0
                });
            }

			var elem = this;
			if (!elem.initialized) {
				elem.dimension = settings.dimension;
                elem.min_dimension = settings.box_min_dimension

				$img = $this.find('img:first');
				elem.old_width = $img.width();
				elem.old_height = $img.height();

				elem.max_param = (elem.old_width >= elem.old_height) ? elem.old_width : elem.old_height;
				elem.min_param = (elem.old_width >= elem.old_height) ? elem.old_height : elem.old_width;

                elem.style.width = elem.min_dimension +'px';
				elem.k = elem.max_param/settings.dimension;
				elem.new_min_param = elem.min_param/elem.k;
				elem.anim_model =  {
					'decrise_all': {'width':elem.min_dimension, 'margin-left':0, 'margin-top':0, 'margin-right':0, 'margin-bottom':0},
					'decrise_img_wide': {'width':elem.max_param, 'margin-left':0, 'margin-top':0, 'margin-right':0},
                    'decrise_img_high': {'height':elem.max_param, 'margin-left':0, 'margin-top':0, 'margin-right':0},
					'incr_img_wide': {'width':elem.dimension, 'margin-left':border_space, 'margin-top':border_space, 'margin-right':border_space, 'margin-bottom':border_space},
					'incr_par_wide': {'width':elem.dimension+border_space*2,'margin-left':-(elem.dimension - elem.min_dimension)/2-border_space, 'margin-top': -(elem.new_min_param - elem.min_param)/2},
					'incr_img_high': {'height':elem.dimension, 'margin-left':border_space, 'margin-top':border_space, 'margin-right':border_space},
					'incr_par_high': {'width':elem.dimension, 'margin-top':-(elem.dimension - elem.max_param)/2, 'margin-left': -(elem.dimension - elem.min_param)/2-border_space+(elem.max_param - elem.min_param)/2}
				}

				elem.initialized = true;
				timeout = setTimeout(do_incrise, settings.delay);
			}
			else
				timeout = setTimeout(do_incrise, settings.delay);
		}

		function do_incrise(){
			$this.unbind('mouseenter mouseleave').mouseleave(do_decrise).css('z-index', 10);

			var big_img = new Image();
			replace_str = 'w'+settings.dimension+'_h'+settings.dimension;
			big_img.src = $img[0].src.replace(/w\d+_h\d+/, replace_str);
			change_class.call(self, 'inc start');
			$img.animate(get_anim_model.call(self, true), settings.speed);
			$this.animate(get_anim_model.call(self, true, true), settings.speed, function(){
				$img.attr('src', big_img.src);
			});
		}

		function do_decrise(){
			$this.unbind('mouseleave').css('z-index', 0);
			change_class.call(self, 'inc');
			$img.animate(get_anim_model.call(self, false), settings.speed);
			$this.animate(get_anim_model.call(self, false, true), settings.speed, function(){
				$this.mouseenter(init_show).mouseleave(cleartime);
                change_class.call(self,'start');
			});
		}

		$this.mouseenter(init_show).mouseleave(cleartime);
	});
}

function getOffset(el, which) {
    var amount = el["offset" + which]
    el = el.offsetParent
    while (el != null) {
	amount += el["offset" + which]
	el = el.offsetParent
    }
    return amount
}

(function($){
	$.fn.display_hover_info = function(hidden_selector, add_class) {
		var add_class = add_class ? add_class : '';
		return this.each( function() {
			$self = $(this);
			$self.mouseenter(function(){
				$this = $(this);
				$this.children(hidden_selector).toggle();
				$this.toggleClass(add_class);
			})
			.mouseleave(function(){
				$(this).mouseenter();
			});
		});
	}
})(jQuery)

function getElementsByNameIE(tag, name) {

    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for(i = 0,iarr = 0; i < elem.length; i++) {
        att = elem[i].getAttribute("name");
        if(att == name) {
            arr[iarr] = elem[i];
            iarr++;
        }
    }
    return arr;
}

opinion_popup_bind = function(ajax_url, page_type)
{
    $$(".opinion.popup, .b-company-info__opinions-bar.b-company-info__opinions-bar_with-popup_yes").mouseenter(function(){
        if (window.popupTimeout != null) {
            clearTimeout(window.opinionPopupTimeout);
        }
        window.popupWindow = $$(this);
        var opinion_id = this.id.split('_')[2];
        var company_site = "0";
        if ($$(this).hasClass('cs')) {
            company_site = "1";
        }
        window.opinionPopupTimeout = window.setTimeout(function(){
            popup_help(window.popupWindow, '', function(cb){
                $$.ajax({
                    url: ajax_url+'/'+opinion_id,
                    type: "GET",
                    dataType: "html",
                    data: {
                        company_site: company_site,
                        page_type: page_type || ''
                    },
                    success: function (data) {
                        cb(data);
                    }
                })
            },
            settings={hide_on_leave: true});
        }, 100);
    });
    $$(".opinion.popup, .b-company-info__opinions-bar.b-company-info__opinions-bar_with-popup_yes").mouseleave(function(){
         if (window.opinionPopupTimeout != null) {
             clearTimeout(window.opinionPopupTimeout);
         }
    });
}

//(function ($) {
jQuery.fn.popup = function (link, o, close_elem) {
    var $link = jQuery(link);
	var $close_elem = jQuery('.'+close_elem);
    var $dlg = this;

    o = jQuery.extend({
        resizable: false,
        autoOpen: false,
        minHeight: 0,
        minWidth: 0
    }, o || {});

    $dlg.dialog(o)
        .parent().addClass("ui-popup")
        .css("padding", 0)
        .mousedown(function (event) { event.stopPropagation();});

    $dlg.siblings(".ui-dialog-titlebar").hide();

    $link.live("click", function (event) {
        var x = jQuery(this).offset().left,
            y = jQuery(this).offset().top,

            scrollLeft = jQuery(document).scrollLeft(),
            scrollTop = jQuery(document).scrollTop();

        $dlg.dialog("option", "position", [x - scrollLeft, y - scrollTop]).dialog("open");

        jQuery(document.body).add($close_elem).mousedown(function () {
            if(!$dlg.data("busy"))
                $dlg.dialog("close");
        });

        event.preventDefault();
        event.stopPropagation();

        //jQuery(window).trigger('scroll');
    }).mousedown(function (event) {
        event.stopPropagation();
    });

    //$("body").click(function () { console.log(1); });
    return this;
}

/* this function is used for block pagination on the new dashboard */
function refreshBlock(page_number, main_container_id) {
    $$('#'+main_container_id).find('.js-pager-content-block').hide().end().
    find('#page-choose-'+page_number+'-content').show();
    // $$('#'+main_container_id).find(".js-pager-content-block:first")
    //     .html($$('#'+main_container_id).find('#page-choose-'+page_number+'-content').find('.js-pager-content-block').html());
    // $$('#'+main_container_id).find(".dashboard-block-header:first").html($$('#'+main_container_id).find('#page-choose-'+page_number+'-content').find('.dashboard-block-header').html());
    $$("#"+main_container_id).data("crnt_page", page_number);
}

function periodicalRotateBlock(pages_number, main_container_id, toggler) {
    if ($$("#"+main_container_id).data("crnt_page") >= pages_number-1) {
        var next_page = 0;
    }
    else {
        var next_page = $$("#"+main_container_id).data("crnt_page")+1;
    }
    SW.c[toggler].click(main_container_id+'-page-choose-'+next_page+'-container');
    refreshBlock(next_page, main_container_id)
}
//})(jQuery);

function on_hide_dashboard_block_click(clicked_elem, request_url) {
    var block = jQuery(clicked_elem).closest('.hideable-dashboard-block');
    var block_id = block[0].id;
    block.trigger('hidden');
    block.remove();
    jQuery.post(request_url, {block_id: block_id});
}

jQuery.fn.ForceNumericOnly =
    function()
    {
        return this.each(function()
        {
            jQuery(this).keyup(function(e)
            {
              if (this.value | -1 === -1) {
              	 var filtered = this.value.replace(/[^0-9]/g, '');
              	 if (filtered != this.value)
                   this.value = filtered;
              }
            }).keydown(function (e)
            {
                var key = e.charCode || e.keyCode || 0;
                // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
                return (
                    key == 8 ||
                    key == 9 ||
                    key == 46 ||
                    (key >= 37 && key <= 40) ||
                    (key >= 48 && key <= 57) ||
                    (key >= 96 && key <= 105));
             })
        })
    };

var in_ = function(elem, arr) {
	for (var i=0; i < arr.length; i++) {
		if (elem == arr[i])
			return true;
	}
	return false;
};

jQuery(document).ajaxSend(function(event, xhr, settings) {
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", jQuery.cookie('csrf_token'));
        if (window.PromUserID) {
            xhr.setRequestHeader("X-PromUserID", window.PromUserID);
        }
    }
});

function roundString(num, after_point) {
    num = Math.floor(num * Math.pow(10, after_point)).toString();
    return [num.slice(0, num.length - after_point), num.slice(num.length - after_point, num.length)].join('.');
}

function send_email_popup(id, type) {
    SW.c["disable_ajax_indicator"] = true;
    var data = {id: id, type: type};
    var url = URLS.send_email_form;
    var overlay_params = {
        closeOnClick: true,
        top: "10",
        fixed: false,
        onClose: function() {$send_email_popup.remove()},
        oneInstance: false,
        mask: "#ccc"
    }

    var $send_email_popup = $$(
            "<div></div>",
            {"id": "send-email-popup", "class": "modal shopping-cart-popup"}
        )
        .append($loading_element)
        .appendTo("body");

    $send_email_popup.overlay(overlay_params).overlay().load();

    $$.getJSON(
        url,
        data,
        function(data){
            $loading_element.replaceWith(data['html']);
            eval(data['js']);
        }
    );

    SW.c["disable_ajax_indicator"] = false;
}
/**
 * Set of tools to make JavaScript better.
 */

var lang = {};

// Use $.isArray, Luke!
// /**
//  * Checks if value is array.
//  */
// lang.isArray = function(v) {
//     if (value instanceof Array) {
//         return true;
//     } else {
//         return false;
//     }
// }
/**
 * Set of parsers.
 */

var parse = {};

(function($) {
    /**
      * Gets script tags from string. Return value is:
      * {'src': src, 'content': content of tag}
      */
    parse.getScriptTags = function(s) {
        var rv = [];

        var built = $(s);
        built.each(function(k, v) {
            if (v.tagName == 'SCRIPT') {
                rv.push({
                    'src': v.getAttribute('src') || "",
                    'content': v.innerHTML
                });
            };

        });
        return rv;
    }
})(jQuery);
/**
 * Ads utils
 */

var ads = {};

(function($) {

    /**
     * 
     */
    ads.evalWithMockedDocumentwrite = function(slot_whole_id, loader_code, logging) {
        if (logging == undefined) {
            logging = false;
        }
        // var logging = true;
        log = function(s) {
            if (logging) {
                console.log(s);
            }
        }
        var do_ = function() {
            window._evalWithMockedDocumentwrite_block = true;
            log('> init: ' + slot_whole_id);
            var timeout_unblock = false;
            document.write = (function(s) {
                log('> writing to: ' + slot_whole_id);
                // log('> write: ' + s);
                $('#' + slot_whole_id).append(s);
                var last_str = function(s) {
                    if (s.indexOf('<em>Я</em>ндекс') >= 0) {
                        log('> last_str returned true');
                        return true;
                    }
                    log('> last_str returned false');
                    return false;
                };
                var shift_or_unblock = function() {
                    if (window._evalWithMockedDocumentwrite_queue.length) {
                        log('> shifting');
                        var f = window._evalWithMockedDocumentwrite_queue.shift();
                        f();
                    } else {
                        log('> removing block');
                        window._evalWithMockedDocumentwrite_block = false;
                    }
                    timeout_unblock = false;
                };
                if (last_str(s)) {
                    shift_or_unblock();
                } else {
                    timeout_unblock = true;
                    window.setTimeout(
                        function() {
                            if (timeout_unblock) {
                                log('> timeout -- launch next ads');
                                shift_or_unblock();
                            }
                        },
                        3000);
                };
            });

            try {
                loader_code();
            } catch (e) {
                log('> exception on writing ads');
                log(e);
            }
        };
            
        if (!window._evalWithMockedDocumentwrite_queue) {
            log('> creating queue');
            window._evalWithMockedDocumentwrite_queue = [];
        }
        if (!window._evalWithMockedDocumentwrite_block) {
            log('> will evaluate do_()');
            return do_();
        } else {
            log('> pushing do_ to queue');
            window._evalWithMockedDocumentwrite_queue.push(do_);
        };
    };

})(jQuery);
/**
  * UI utils
  */

var ui = {};

(function($) {
    ui.login_popup = function(trigger, handler) {

        trigger.click(function() {
            var $signin_popup_content = $$(
                '<div></div>',
                {'id': 'login-form-popup-content'}
            );
            var $signin_popup = $$(
                '<div></div>',
                {'id': 'login-form-popup', 'class': 'modal help-popup'}
            ).append($signin_popup_content).appendTo('body');

            var overlay_params = {
                top: "20%",
                load: false, // overlay called with a load() method after ajax is loaded
                fixed: false,
                closeOnClick: false,
                oneInstance: false,
                onClose: function() {
                    $signin_popup.remove();
                }
            }            
            $$.getJSON(
                URLS.login_form,
                {},
                function(data) {
                    $signin_popup_content.replaceWith(data['html']);
                    eval(data['js']);
                    $('#submit_login_button').click(function(){
                        SW.validateSubmitForm({
                            button: this,
                            validationSuccess: function (json, textStatus, xhr) {
                                $signin_popup.remove();
                                handler(json);
                            }
                        });
                        return false;
                    });
                    $signin_popup.overlay(overlay_params).overlay().load();
                }
            );
        });
    };
})(jQuery);


(function($) {
    var TabControl = {
        options: {
            control: null,
            panel: null,
            pager: null,
            selected: -1
        },

        _init: function() {
            var self = this;
            var e = $(this.element);
            var o = this.options;
            o.control = e;
            o.panel = e.find('.b-tabs-panel');
            o.pager = e.find('.b-tabs-pager');
            o.pager_ul = o.pager.find("ul");
            var select = o.selected;
            o.selected = -1;
            this._select_tab(select);
            o.pager_ul.delegate('li', 'click', function(e) {
                var parent = $(e.currentTarget).parent();
                self._select_tab(parent.children().index(e.currentTarget));
                return false;
            });
        },

        _select_tab: function(i) {
            i = (i||0) + 1;
            if (i === this.options.selected) { return; }
            var o = this.options;
            var container = o.panel.children(":nth-child("+i+")");
            o.pager_ul.children().removeClass('b-tabs-page_active');
            o.pager_ul.children(":nth-child("+i+")").addClass('b-tabs-page_active');
            var current = o.panel.children(":nth-child("+i+")");
            current.fadeIn(200);
            o.panel.children().not(current).hide(100);
            //this.options.panel.fadeOut(100).animate({'margin-left': (i - 1)*(-683)}, 0).fadeIn(200);
            this._show_images(container);
            o.selected = i;
        },

        _show_images: function(container) {
            container.find("img.img-ondemand").trigger("appear");
        }
    };

    $.widget('ui.tabby', TabControl);
})(jQuery);

(function($) {
    var ComixControl = {
        options: {
            control: null,
            panel: null,
            pager: null,
            next_button: null,
            prev_button: null,
            text: null,
            selected: 1,
            pages: 0,
            page_width: 0,
            speed: 300,
            cls_button_prev: "b-comix-prev",
            cls_button_next: "b-comix-next",
            cls_text: "b-comix-text",
            texts: []
        },

        _init: function() {
            var self = this;
            var e = $(this.element);
            var o = this.options;
            o.control = e;
            o.panel = e.find(".b-comix-scroll");
            o.controls = e.find(".b-comix-controls");
            this._create_controls(o);
            this._set_page(o.selected);
        },

        _create_controls: function(o) {
            var created_controls = [];
            function add_control(id) {
                var control = o.control.find("."+id);
                if (control.length === 0) {
                    control = $("<span></span>", {'class': id});
                    created_controls.push(control);
                }
                return control;
            }

            o.text = add_control(o.cls_text);
            o.next_button = add_control(o.cls_button_next);
            o.prev_button = add_control(o.cls_button_prev);
            for(var i=created_controls.length; i--; i<=0)
                o.controls.append(created_controls[i]);
            var self = this;
            o.next_button.bind("click", function() {
                self.next();
            });
            o.prev_button.bind("click", function() {
                self.prev();
            });
        },

        _set_page: function(page) {
            var o = this.options;
            if (page < 1 || page > o.pages) {
                return;
            }
            if (o.selected != page)
                o.panel.animate({'margin-left': -1*(page-1)*o.page_width+'px' }, o.speed);
            o.selected = page;
            this._update_buttons_state(o);
        },

        _update_buttons_state: function(o)
        {
            function set_button_state(button, id, disable) {
                var new_state = "active";
                var old_state = "disabled";
                if (disable) {
                    old_state = "active";
                    new_state = "disabled";
                }
                button.addClass('icon-'+id+'_'+new_state);
                button.removeClass('icon-'+id+'_'+old_state);
            }
            set_button_state(o.prev_button, "button_prev", o.selected == 1);
            set_button_state(o.next_button, "button_next", o.selected == o.pages);
            this._update_text(o);
        },

        _update_text: function(o)
        {
            o.text.html(o.texts[o.selected-1]);
        },

        next: function() {
            this._set_page(this.options.selected+1);
        },

        prev: function() {
            this._set_page(this.options.selected-1);
        }

    };

    $.widget('ui.comix', ComixControl);
})(jQuery);

(function($) {
    var FloatPanel = {
        options: {
            content: null,
            top: '30%',
            width: 300,
            animation_speed: 500
        },

        _init: function() {
            this._create_panel();
        },

        _create_panel: function() {
            var html = '<div id="float-panel" class="float-panel-closed"> \
                    <div class="float-panel__visible"> \
                        <span class="float-panel__visible-arrow float-panel__visible-arrow-l">&laquo;</span> \
                        <span class="float-panel__visible-arrow float-panel__visible-arrow-r">&raquo;</span> \
                    </div> \
                    <div class="float-panel__content" style="display: none"> \
                        '+ this.element.html() +' \
                    </div> \
                </div>';
            $(html).appendTo('body');
            this.panel = $('#float-panel');
            this.panel.width(this.options.width);
            this.panel_content = this.panel.find('.float-panel__content');
            this.panel.css('top', this.options.top);
            this.panel.find('.float-panel__visible, .float-panel__content').height(this.panel.height());
            this.panel_visible_width = this.panel.find('.float-panel__visible').width()
            this.panel.css('right', (this.options.width - this.panel_visible_width) * -1);
            var self = this;
            this.panel.find('.float-panel__visible-arrow').click(function() {
                if (self.panel_content.is(':visible')) {
                    self.hide_panel();
                } else {
                    self.show_panel();
                }
            });
            $(document).bind('show.floatpanel', function(){
                self.show_panel();
            })
        },

        hide_panel: function() {
            var self = this;
            this.panel.animate({
                right: (this.options.width - this.panel_visible_width) * -1
            }, this.options.animation_speed, function() {
                self.panel.addClass('float-panel-closed');
            });
            this.panel_content.fadeOut(this.options.animation_speed * 1.5);
            $(document).trigger('on_hide.floatpanel');
        },

        show_panel: function() {
            var self = this;
            this.panel.animate(
                {right: 0},
                this.options.animation_speed,
                function() {
                    self.panel.removeClass('float-panel-closed');
                }
            );
            this.panel_content.fadeIn(this.options.animation_speed * 1.5)
            $(document).trigger('on_show.floatpanel');
        }
    };

    $.widget('ui.floatpanel', FloatPanel);
})(jQuery);

(function($) {
    ui.init_categories = function() {

        var config = {
             over: show_panel,
             timeout: 100,
             out: hide_panel
        };
        $("#categories-top .b-categories-top__item").hoverIntent(config);
        $("#categories-top-collapsed .b-categories-top__item").hoverIntent(config);

        function show_panel(e) {
            var elem = $(e.currentTarget);
            var panel = elem.children('div');
            var window_h = $(window).height();
            var space = window_h - (elem.offset().top - $(document).scrollTop())-panel.height()-15;
            if (space > 0) space=0;
            if (window_h < panel.height()) space=space+(panel.height()-window_h+25);
            panel.css({top: space+'px'});
            panel.fadeIn(200);
            panel.find(".img-ondemand-no-scroll").trigger('appear');
        }
        function hide_panel(e) {
            var panel = $(e.currentTarget).children('div');
            panel.fadeOut(100);
        }
    }
})(jQuery);

(function($) {
    var ConfirmDialog = {
        options: {
            header: null,
            content: null,
            callback: null,
            event: 'click'
        },

        _init: function() {
            var _url;
            var _this = this;
            var html = '<div class="b-overlay b-overlay_type_dialog">';
            html += '<div class="b-overlay__header">'+ this.options.header +'</div>';
            html += '<div class="b-overlay__content">';
            html += this.options.content;
            html += '<div class="b-overlay__content-dialogbuttons">';
            for (var type in this.options.buttons) {
                var btn = this.options.buttons[type],
                    label = btn.label;

                html += '<button data-type="' + type + '" type="button" class="b-overlay__button">'+ label +'</button>';
            }
            html += '</div></div></div>';

            var $html = $(html);
            $html.appendTo($('body'));

            var overlay = $html.overlay({
                top: 'center',
                mask: {
                    color: '#929292'
                },
                oneInstance: false,
                closeOnClick: false
            });

            var buttons = overlay.find('button').click(function(){
                var button = jQuery(this);
                var type = button.data('type');

                var btn_config = _this.options.buttons;

                if (btn_config[type].enabled === true) {
                    _this.options.callback(_url);
                }
                $html.data('overlay').close();
            });

            $(_this.element).bind(_this.options.event, function(e){
                _url = $(this).prop('href');
                $html.data('overlay').load();
                return false;
            });
        }
    };

    $.widget('ui.confirmdialog', ConfirmDialog);
})(jQuery);/* jquery.hoverintent.js */
(function($) {
  $.fn.hoverIntent = function(f, g) {
    var cfg = {sensitivity:7, interval:100, timeout:0};
    cfg = $.extend(cfg, g ? {over:f, out:g} : f);
    var cX, cY, pX, pY;
    var track = function(ev) {
      cX = ev.pageX;
      cY = ev.pageY
    };
    var compare = function(ev, ob) {
      ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
      if(Math.abs(pX - cX) + Math.abs(pY - cY) < cfg.sensitivity) {
        $(ob).unbind("mousemove", track);
        ob.hoverIntent_s = 1;
        return cfg.over.apply(ob, [ev])
      }else {
        pX = cX;
        pY = cY;
        ob.hoverIntent_t = setTimeout(function() {
          compare(ev, ob)
        }, cfg.interval)
      }
    };
    var delay = function(ev, ob) {
      ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
      ob.hoverIntent_s = 0;
      return cfg.out.apply(ob, [ev])
    };
    var handleHover = function(e) {
      var ev = jQuery.extend({}, e);
      var ob = this;
      if(ob.hoverIntent_t) {
        ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t)
      }
      if(e.type == "mouseenter") {
        pX = ev.pageX;
        pY = ev.pageY;
        $(ob).bind("mousemove", track);
        if(ob.hoverIntent_s != 1) {
          ob.hoverIntent_t = setTimeout(function() {
            compare(ev, ob)
          }, cfg.interval)
        }
      }else {
        $(ob).unbind("mousemove", track);
        if(ob.hoverIntent_s == 1) {
          ob.hoverIntent_t = setTimeout(function() {
            delay(ev, ob)
          }, cfg.timeout)
        }
      }
    };
    return this.bind("mouseenter", handleHover).bind("mouseleave", handleHover)
  }
})(jQuery);
/* jquery.hoverintent.js end */

